/**
 * 应用头部组件
 * 负责管理应用头部的交互功能，包括主题切换和设置按钮
 */
class AppHeader {  constructor() {
    this.themes = ['blue', 'dark', 'light'];
    this.currentThemeIndex = 0;
    this.themeBtn = null;
    this.settingsBtn = null;
    this.settingsModel = null;
      // 导航相关
    this.chatNavBtn = null;
    this.documentNavBtn = null;
    this.workflowNavBtn = null;
    this.sessionsNavBtn = null;
    this.currentView = 'chat'; // 当前视图：'chat'、'document' 或 'workflow'
    
    // 会话列表相关
    this.sessionDropdown = null;
    this.sessionList = null;
    this.sessionLoading = null;
    this.closeSessionBtn = null;
    this.isSessionDropdownVisible = false;
    this.currentUserId = 'default-user'; // 默认用户ID，实际应用中应从认证系统获取
    
  }

  /**
   * 初始化头部组件
   */
  async init() {
    await this.loadHeaderHTML();
    this.bindElements();
    this.bindEvents();
    this.loadTheme();
  }

  /**
   * 加载头部HTML内容
   */
  async loadHeaderHTML() {
    try {
      const response = await fetch('./components/app-header.html');
      const headerHTML = await response.text();
      
      // 查找现有的header元素并替换
      const existingHeader = document.querySelector('.app-header');
      if (existingHeader) {
        existingHeader.outerHTML = headerHTML;
      } else {
        // 如果没有现有header，在body开头插入
        document.body.insertAdjacentHTML('afterbegin', headerHTML);
      }
    } catch (error) {
      console.error('加载头部HTML失败:', error);
    }
  }  /**
   * 绑定DOM元素
   */
  bindElements() {    this.themeBtn = document.getElementById('theme-btn');
    this.settingsBtn = document.getElementById('settings-btn');
    this.chatNavBtn = document.getElementById('chat-nav-btn');
    this.documentNavBtn = document.getElementById('document-nav-btn');
    this.workflowNavBtn = document.getElementById('workflow-nav-btn');
    this.sessionsNavBtn = document.getElementById('sessions-nav-btn');
    
    // 会话列表相关元素
    this.sessionDropdown = document.getElementById('session-dropdown');
    this.sessionList = document.getElementById('session-list');
    this.sessionLoading = document.getElementById('session-loading');
    this.closeSessionBtn = document.getElementById('close-session-dropdown');
  }  /**
   * 绑定事件监听器
   */
  bindEvents() {
    // 主题切换按钮事件
    if (this.themeBtn) {
      this.themeBtn.addEventListener('click', () => this.switchTheme());
    }

    // 设置按钮事件
    if (this.settingsBtn) {
      this.settingsBtn.addEventListener('click', () => this.openSettings());
    }

    // 导航按钮事件
    if (this.chatNavBtn) {
      this.chatNavBtn.addEventListener('click', () => this.switchToView('chat'));
    }    if (this.documentNavBtn) {
      this.documentNavBtn.addEventListener('click', () => this.switchToView('document'));
    }

    if (this.workflowNavBtn) {
      this.workflowNavBtn.addEventListener('click', () => this.switchToView('workflow'));
    }

    // 会话列表按钮事件
    if (this.sessionsNavBtn) {
      this.sessionsNavBtn.addEventListener('click', () => this.toggleSessionDropdown());
    }

    // 关闭会话下拉框按钮事件
    if (this.closeSessionBtn) {
      this.closeSessionBtn.addEventListener('click', () => this.hideSessionDropdown());
    }

    // 点击外部区域关闭会话下拉框
    document.addEventListener('click', (event) => {
      if (this.isSessionDropdownVisible && 
          !this.sessionDropdown.contains(event.target) && 
          !this.sessionsNavBtn.contains(event.target)) {
        this.hideSessionDropdown();
      }
    });
  }

  /**
   * 设置settings模型实例
   */
  setSettingsModel(settingsModel) {
    this.settingsModel = settingsModel;
  }

  /**
   * 打开设置
   */
  openSettings() {
    if (this.settingsModel) {
      this.settingsModel.show();
    } else {
      console.warn('设置模型未初始化');
    }
  }

  /**
   * 从本地存储加载主题
   */
  loadTheme() {
    const savedTheme = localStorage.getItem('chatAppTheme') || 'blue';
    const themeIndex = this.themes.indexOf(savedTheme);
    this.currentThemeIndex = themeIndex >= 0 ? themeIndex : 0;
    this.applyTheme(this.themes[this.currentThemeIndex]);
  }

  /**
   * 应用主题
   */
  applyTheme(theme) {
    document.body.setAttribute('data-theme', theme);
    
    // 更新主题按钮图标
    const themeIcons = {
      'blue': '🌊',
      'dark': '🌙', 
      'light': '☀️'
    };
    
    if (this.themeBtn) {
      this.themeBtn.textContent = themeIcons[theme];
      this.themeBtn.title = `当前主题: ${theme === 'blue' ? '蓝色' : theme === 'dark' ? '黑色' : '白色'}`;
    }
  }

  /**
   * 切换主题
   */
  switchTheme() {
    this.currentThemeIndex = (this.currentThemeIndex + 1) % this.themes.length;
    const newTheme = this.themes[this.currentThemeIndex];
    
    this.applyTheme(newTheme);
    
    // 保存到本地存储
    localStorage.setItem('chatAppTheme', newTheme);
    
    // 添加切换动画效果
    document.body.style.transition = 'all 0.3s ease';
    setTimeout(() => {
      document.body.style.transition = '';
    }, 300);
  }

  /**
   * 获取当前主题
   */
  getCurrentTheme() {
    return this.themes[this.currentThemeIndex];
  }
  /**
   * 设置主题（编程方式）
   */
  setTheme(theme) {
    const themeIndex = this.themes.indexOf(theme);
    if (themeIndex >= 0) {
      this.currentThemeIndex = themeIndex;
      this.applyTheme(theme);
      localStorage.setItem('chatAppTheme', theme);
    }
  }

  /**
   * 切换到指定视图
   */
  switchToView(view) {
    if (this.currentView === view) return;

    this.currentView = view;
    
    // 更新按钮状态
    this.updateNavButtons();
    
    // 触发视图切换事件
    document.dispatchEvent(new CustomEvent('viewChanged', {
      detail: { view: view }
    }));
  }
  /**
   * 更新导航按钮状态
   */
  updateNavButtons() {
    if (this.chatNavBtn && this.documentNavBtn && this.workflowNavBtn) {
      this.chatNavBtn.classList.toggle('active', this.currentView === 'chat');
      this.documentNavBtn.classList.toggle('active', this.currentView === 'document');
      this.workflowNavBtn.classList.toggle('active', this.currentView === 'workflow');
    }
  }

  /**
   * 获取当前视图
   */
  getCurrentView() {
    return this.currentView;
  }

  /**
   * 切换会话下拉框显示/隐藏
   */
  toggleSessionDropdown() {
    if (this.isSessionDropdownVisible) {
      this.hideSessionDropdown();
    } else {
      this.showSessionDropdown();
    }
  }

  /**
   * 显示会话下拉框并加载会话列表
   */
  async showSessionDropdown() {
    if (!this.sessionDropdown) return;
    
    this.sessionDropdown.classList.remove('hidden');
    this.isSessionDropdownVisible = true;
    
    // 加载会话列表
    await this.loadSessions();
  }

  /**
   * 隐藏会话下拉框
   */
  hideSessionDropdown() {
    if (!this.sessionDropdown) return;
    
    this.sessionDropdown.classList.add('hidden');
    this.isSessionDropdownVisible = false;
  }
  /**
   * 加载会话列表
   */
  async loadSessions() {
    if (!this.sessionList || !this.sessionLoading) return;
    
    // 显示加载状态
    this.sessionLoading.style.display = 'flex';
    this.sessionList.innerHTML = '<div class="loading-indicator" id="session-loading"><div class="spinner"></div><span>加载中...</span></div>';
    
    try {
      // 使用SessionAPI获取会话列表
      if (!window.SessionAPI) {
        throw new Error('SessionAPI未加载');
      }
      
      const sessionAPI = new window.SessionAPI();
      const sessions = await sessionAPI.getSessions(this.currentUserId);
      
      // 渲染会话列表
      this.renderSessions(sessions);
      
    } catch (error) {
      console.error('加载会话列表失败:', error);
      this.renderError('加载会话列表失败，请稍后重试');
    }
  }

  /**
   * 渲染会话列表
   */
  renderSessions(sessions) {
    if (!this.sessionList) return;
    
    if (!sessions || sessions.length === 0) {
      this.sessionList.innerHTML = `
        <div class="empty-message">
          暂无会话记录
        </div>
      `;
      return;
    }

    const sessionItems = sessions.map(session => `
      <div class="session-item" data-session-id="${session.sessionId}">
        <div class="session-icon">💬</div>
        <div class="session-info">
          <p class="session-name">${this.escapeHtml(session.sessionName)}</p>
          <p class="session-id">ID: ${this.escapeHtml(session.sessionId)}</p>
        </div>
      </div>
    `).join('');

    this.sessionList.innerHTML = sessionItems;

    // 绑定会话项点击事件
    const sessionItemElements = this.sessionList.querySelectorAll('.session-item');
    sessionItemElements.forEach(item => {
      item.addEventListener('click', () => {
        const sessionId = item.getAttribute('data-session-id');
        this.selectSession(sessionId);
      });
    });
  }

  /**
   * 渲染错误信息
   */
  renderError(message) {
    if (!this.sessionList) return;
    
    this.sessionList.innerHTML = `
      <div class="error-message">
        ${this.escapeHtml(message)}
      </div>
    `;
  }

  /**
   * 选择会话
   */
  selectSession(sessionId) {
    console.log('选择会话:', sessionId);
    
    // 触发会话选择事件
    document.dispatchEvent(new CustomEvent('sessionSelected', {
      detail: { sessionId: sessionId }
    }));
    
    // 隐藏下拉框
    this.hideSessionDropdown();
  }

  /**
   * 设置当前用户ID
   */
  setUserId(userId) {
    this.currentUserId = userId;
  }

  /**
   * 获取当前用户ID
   */
  getUserId() {
    return this.currentUserId;
  }

  /**
   * HTML转义工具方法
   */
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }
}

// 导出组件类供其他模块使用
window.AppHeader = AppHeader;
